/*
 * Check anagram for two strings
 *
 * @version  1.0 27 Jan 2013
 * @author Myhaylo Kotsyuruba (javatrainee15)
 */
 
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;

public class Anagram {
    public static void main(String[] args) {
        String phraseA = getPhrase("phrase A");
        String phraseB = getPhrase("phrase B");
        boolean isAnagram = checkAnagram(phraseA, phraseB);
        showResult(isAnagram);
    }
    
    static String getPhrase(String annotation) {
        System.out.print("Input " + annotation + ": ");
        Scanner inputFromKeybord = new Scanner(System.in);
        String inputString = inputFromKeybord.nextLine();
        return inputString;
    }
    
    static boolean checkAnagram(String expressionA, String expressionB) {
        expressionA = normalizeString(expressionA);
        expressionB = normalizeString(expressionB);
        return expressionA.equals(expressionB);
    }
    
    static String normalizeString (String expression) {
        int[] codepoints = stringToCodepoint(expression);
        int[] letterCodepoints = selectLetterOnly(codepoints);
        int[] smallLetterCodepoints = codepointToLowerCase(letterCodepoints);
        Arrays.sort(smallLetterCodepoints);
        return new String(smallLetterCodepoints, 0, smallLetterCodepoints.length);
    }
    
    static int[] stringToCodepoint(String phrase) {
        int[] codePoints = new int[phrase.length()];
        for (int index = 0; index < phrase.length(); index++) {
            codePoints[index] = phrase.codePointAt(index);
        }
        return codePoints;
    }
    
    static int[] selectLetterOnly(int[] codes) {
        int lengthLetterArray = 0;
        for(int someCode : codes) {
            if (Character.isLetter(someCode)) {
                lengthLetterArray++;
            }
        }
        
        int[] result = new int[lengthLetterArray];
        int indexLetterArray = 0;
        for(int someCode : codes) {
            if (Character.isLetter(someCode)) {
                result[indexLetterArray] = someCode;
                indexLetterArray++;
            }
        }
        return result;
    }
    
    static int[] codepointToLowerCase(int[] someCodepoints) {
        for(int indexCodepoints = 0; indexCodepoints < someCodepoints.length; indexCodepoints++) {
            someCodepoints[indexCodepoints] = Character.toLowerCase(someCodepoints[indexCodepoints]);
        }
        return someCodepoints;
    }
    
    static void showResult(boolean condition) {
        if (condition) {
            System.out.println("Answer: They ARE anagrams!");
        } else {
            System.out.println("Answer: They are NOT anagrams!");
        }
    }
}

